<template>
  <div class="file-selector">
    <div class="selector-content">
      <!-- Version selection -->
      <div class="selection-section">
        <h4>选择历史版本</h4>
        <el-select
          v-model="selectedVersion"
          placeholder="请选择历史版本"
          @change="onVersionChange"
          style="width: 100%"
        >
          <el-option
            v-for="version in historyStore.versions"
            :key="version.id"
            :label="`版本 ${version.id} (${formatDate(version.timestamp)})`"
            :value="version.id"
          />
        </el-select>
      </div>

      <!-- File tree -->
      <div class="selection-section" v-if="selectedVersion">
        <h4>选择文件</h4>
        <div class="file-tree-container">
          <el-tree
            ref="treeRef"
            :data="fileTree"
            :props="treeProps"
            node-key="id"
            :expand-on-click-node="false"
            @node-click="onNodeClick"
            class="file-tree"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <el-icon v-if="data.type === 'folder'">
                  <Folder v-if="!node.expanded" />
                  <FolderOpened v-else />
                </el-icon>
                <el-icon v-else>
                  <Document />
                </el-icon>
                <span class="node-label">{{ data.name }}</span>
                <span v-if="data.type === 'file'" class="file-info">
                  {{ formatFileSize(data.size) }}
                </span>
              </div>
            </template>
          </el-tree>
        </div>
      </div>

      <!-- Selected file info -->
      <div class="selection-section" v-if="selectedFile">
        <h4>已选择文件</h4>
        <el-card class="selected-file-card">
          <div class="file-details">
            <div class="detail-row">
              <span class="label">文件路径:</span>
              <span class="value">{{ selectedFile.path }}</span>
            </div>
            <div class="detail-row">
              <span class="label">文件大小:</span>
              <span class="value">{{ formatFileSize(selectedFile.size) }}</span>
            </div>
            <div class="detail-row">
              <span class="label">修改时间:</span>
              <span class="value">{{ formatDate(selectedFile.timestamp) }}</span>
            </div>
          </div>
          <el-button 
            type="primary" 
            @click="confirmSelection"
            style="width: 100%; margin-top: 12px;"
          >
            确认选择此文件
          </el-button>
        </el-card>
      </div>

      <!-- Empty state -->
      <div v-if="!selectedVersion" class="empty-state">
        <el-empty description="请先选择一个历史版本" />
      </div>
      
      <div v-else-if="!fileTree.length" class="empty-state">
        <el-empty description="该版本中没有文件" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useHistoryStore } from '../stores'
import { Folder, FolderOpened, Document } from '@element-plus/icons-vue'
import type { FileTreeNode } from '../types/basic'

interface Props {
  placeholder?: string
}

interface Emits {
  (e: 'file-selected', selection: { versionId: string, fileId: string, path: string }): void
}

withDefaults(defineProps<Props>(), {
  placeholder: '选择文件'
})

const emit = defineEmits<Emits>()

const historyStore = useHistoryStore()

// Component state
const selectedVersion = ref<string>('')
const selectedFile = ref<FileTreeNode | null>(null)
const treeRef = ref()

// Tree configuration
const treeProps = {
  children: 'children',
  label: 'name',
  isLeaf: (data: FileTreeNode) => data.type === 'file'
}

// Computed properties
const fileTree = computed(() => {
  if (!selectedVersion.value) return []
  return historyStore.getVersionFiles(selectedVersion.value) || []
})

// Methods
const onVersionChange = async (versionId: string) => {
  selectedFile.value = null
  if (versionId) {
    await historyStore.loadVersionFiles(versionId)
  }
}

const onNodeClick = (data: FileTreeNode) => {
  if (data.type === 'file') {
    selectedFile.value = data
  }
}

const confirmSelection = () => {
  if (selectedFile.value && selectedVersion.value) {
    emit('file-selected', {
      versionId: selectedVersion.value,
      fileId: selectedFile.value.id,
      path: selectedFile.value.path
    })
  }
}

const formatDate = (timestamp?: number) => {
  if (!timestamp) return '未知时间'
  return new Date(timestamp).toLocaleString('zh-CN')
}

const formatFileSize = (size?: number) => {
  if (!size) return '未知'
  
  const units = ['B', 'KB', 'MB', 'GB']
  let unitIndex = 0
  let fileSize = size
  
  while (fileSize >= 1024 && unitIndex < units.length - 1) {
    fileSize /= 1024
    unitIndex++
  }
  
  return `${fileSize.toFixed(1)} ${units[unitIndex]}`
}

// Initialize
onMounted(async () => {
  await historyStore.loadVersions()
})

// Watch for version changes
watch(selectedVersion, (newVersion) => {
  if (newVersion) {
    onVersionChange(newVersion)
  }
})
</script>

<style scoped>
.file-selector {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.selector-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.selection-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.selection-section h4 {
  margin: 0;
  color: var(--el-text-color-primary);
  font-size: 14px;
  font-weight: 600;
}

.file-tree-container {
  flex: 1;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  overflow: auto;
  max-height: 200px;
}

.file-tree {
  padding: 8px;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 6px;
  width: 100%;
}

.node-label {
  flex: 1;
  font-size: 13px;
}

.file-info {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.selected-file-card {
  border: 1px solid var(--el-color-primary-light-7);
  background-color: var(--el-color-primary-light-9);
}

.file-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
}

.label {
  font-weight: 600;
  color: var(--el-text-color-regular);
}

.value {
  color: var(--el-text-color-primary);
  font-family: monospace;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Tree styling overrides */
:deep(.el-tree-node__content) {
  height: 32px;
  padding: 0 8px;
}

:deep(.el-tree-node__content:hover) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: var(--el-color-primary-light-8);
  color: var(--el-color-primary);
}

:deep(.el-tree-node__expand-icon) {
  padding: 4px;
}
</style>